import json
from urllib.parse import urlencode

import requests
import config

api_host = 'https://flash.flashxsport.com'
total_count = 0
finish_events_url = api_host + '/flash/activity/clubActRecord?clubId={0}&keyWord=&pageSize={1}&pageNo=1&longitude=116.4&latitude=39.9&isLoading=false&isHave=true&type=-1&aaStatus=-1&actStatus=3&actTime=-1&sportId=0'
fetch_users_url = f'{api_host}/flash/clubMember/searchMember?clubId={config.club_id}&keyword=&pageSize={config.page_size}&isLoading=true&isHave=true&sportId=1&sortCate=1&sortWay=2' + '&pageNo={0}'
activity_detail_url = f'{api_host}/flash/activity/detail?latitude=39.9&longitude=116.4' + '&activityId={0}'
act_group_list_url = f'{api_host}/flash/activityGroup/groupListWithInitMember?pageSize=10000' + '&activityId={0}'
get_openid_url = f'https://api.weixin.qq.com/sns/jscode2session?appid={config.APP_ID}&secret={config.APP_SECRET}&grant_type=authorization_code&js_code=' + '{0}'
get_club_credit_url = f'{api_host}/flash/clubAlliance/clubLevel?clubId=' + '{0}'
get_club_comments_url = f'{api_host}/flash/clubEvaluate/clubEvaluateList?clubId=' + '{0}&pageSize=99&pageNo={1}'
get_my_act_url = f'{api_host}/flash/activity/userActivityList?pageNo=1&pageSize=200&keyWord=&longitude=116.22299194335938&latitude=39.90568923950195&sportId=0'
create_comment_url = f'{api_host}/flash/clubEvaluate/create'
login_url = f'{api_host}/flash/auth/loginByPwd'
# POST {"activityId":"000000","memberIdList":[1045421]}
add_temp_admin_url = f'{api_host}/flash/actTempAdmin/add'
list_temp_admin_url = f'{api_host}/flash/actTempAdmin/list?activityId=' + '{0}&sportId=1'
# {"success":true,"message":"操作成功！","code":200,"result":{"nickName":"椰子","openId":"oMick5YZB41MyU3pwVgUo4aI73WE","realName":null,"idNumber":null,"phone":"15810242357","avatar":"https://oss.flashxsport.com/flashUpload/userAvatar/tmp_ff8041876908fe538d0a2e5687a04b36_20747574672473197.jpg","sex":0,"xbSex":0,"balance":0.00,"province":null,"city":null,"region":null,"level":1.0,"height":null,"weight":null,"isWithdrawOrder":0,"orderNo":null,"userId":4172061,"campaignId":1,"sportId":null,"yxUid":null,"yxAuthStatus":0,"blockChainAddress":null,"cardType":1,"birthday":null,"isSubscribeOfficial":0,"isSetPwd":0,"isNotSavaPhone":null,"bgImg":null},"timestamp":1761539720920}
get_my_info_url = f'{api_host}/flash/user/getUserInfo?sportId=1'
club_act_list_url = f'{api_host}/flash/activity/filterList?longitude=116.40717315673828&latitude=39.90468978881836&searchDate=&type=1&id=' + '{0}&pageSize=30&pageNo=1&sportId=0'

# 羽毛球首页活动列表
top_act_url = f'{api_host}/flash/activity/list?pageNo=1&pageSize=3&sortRule=0&latitude=39.90568923950195&longitude=116.22299194335938&area=&city=%E5%8C%97%E4%BA%AC%E5%B8%82&nearby=&date=&levelLower=1&levelUpper=9&sportId=1&isQueryFreePlayAct=0'
# 石景山  %E7%9F%B3%E6%99%AF%E5%B1%B1%E5%8C%BA
bad_act_list_url = api_host + '/flash/activity/list?pageNo=1&pageSize={0}&sortRule=0&latitude=39.95933151245117&longitude=116.29844665527344&area={1}&city=%E5%8C%97%E4%BA%AC%E5%B8%82&nearby=&date=&levelLower=1&levelUpper=9&sportId=1&isQueryFreePlayAct=0'


class HttpHelper:
    def __init__(self):
        self.flash_token = None

    def set_flash_token(self, token):
        self.flash_token = token

    def fetch_club_members(self, page_no):
        url = fetch_users_url.format(page_no)
        return self.__fetch_flashx__(url)

    def fetch_club_activities(self, club_id):
        url = club_act_list_url.format(club_id)
        return self.__fetch_flashx__(url)

    def fetch_club_finish_events(self, club_id, page_size):
        return self.__fetch_flashx__(finish_events_url.format(club_id, page_size))

    def fetch_club_comments(self, club_id, page):
        url = get_club_comments_url.format(club_id, page)
        # print('url is:', url)
        return self.__fetch_flashx__(url)

    def fetch_activity_detail(self, act_id):
        url = activity_detail_url.format(act_id)
        # print('url:', url)
        return self.__fetch_flashx__(url)

    def fetch_activity_group_list(self, act_id):
        url = act_group_list_url.format(act_id)
        return self.__fetch_flashx__(url)

    def get_openid(self, code):
        url = get_openid_url.format(code)
        return self.__fetch__(url).json()
        # return {'openid': 'abcdefghijklmn'}

    # 抓取羽毛球分类第一页的活动列表，用于投放效果分析
    def fetch_top_activities(self, page_size, region):
        url = bad_act_list_url.format(page_size, region)
        return self.__fetch_flashx__(url)

    def fetch_club_credit(self, club_id):
        url = get_club_credit_url.format(club_id)
        return self.__fetch_flashx__(url)

    def fetch_my_act(self):
        url = get_my_act_url
        return self.__fetch_flashx__(url)

    def create_comment(self, data):
        url = create_comment_url
        return self.__post_flashx__(url, data)

    def login_in(self, phone, pwd):
        url = login_url
        data = {"phone": phone, "pwd": pwd}
        return self.__post_flashx__(url, data)

    def create_act(self, data):
        url = f'{api_host}/flash/activity/publishActivity'
        return self.__post_flashx__(url, data)

    def get_act_group(self, act_id):
        url = f'{api_host}/flash/activity/getApplyInfo?activityId={act_id}'
        return self.__fetch_flashx__(url)

    def get_my_info(self):
        # {"success":true,"message":"操作成功！","code":200,"result":{"nickName":"小小鱼","openId":null,"realName":null,"idNumber":null,"phone":"13264236238","avatar":"http://oss.flashxsport.com/staticImg/static/app/login/avatar2.png","sex":0,"xbSex":0,"balance":0.00,"province":null,"city":null,"region":null,"level":1.0,"height":160,"weight":60.0,"isWithdrawOrder":0,"orderNo":null,"userId":4821669,"campaignId":null,"sportId":null,"yxUid":null,"yxAuthStatus":0,"blockChainAddress":null,"cardType":1,"birthday":null,"isSubscribeOfficial":0,"isSetPwd":1,"isNotSavaPhone":null,"bgImg":null},"timestamp":1760933985620}
        pass

    def get_my_clubs(self):
        return self.__fetch_flashx__(get_my_club_url)

    ################################################################ 用户注册部分api ##############################################################
    def get_sms_code(self, phone):
        url = f'{api_host}/flash/auth/verificationCode'
        data = {'phone': phone, 'smsMode': 0}
        # {"success":true,"message":"操作成功！","code":200,"result":"短信验证码发送成功!","timestamp":1761539670900}
        return self.__post_flashx__(url, data)

    def login_by_sms_code(self, phone, code):
        url = f'{api_host}/flash/auth/loginBySms'
        data = {'phone': phone, 'verifyCode': code}
        # {"success":true,"message":"操作成功！","code":200,"result":{"userType":1,"users":[{"id":4172061,"version":null,"createTime":"2025-07-25 12:40:40","updateTime":null,"delFlag":0,"password":null,"nickName":"椰子","realName":null,"idNumber":null,"xbSex":null,"phone":"15810242357","avatar":"flashUpload/userAvatar/tmp_ff8041876908fe538d0a2e5687a04b36_20747574672473197.jpg","sex":0,"campaignId":null,"openId":"oMick5YZB41MyU3pwVgUo4aI73WE","mpOpenId":null,"unionId":null,"province":null,"city":null,"region":null,"salt":null,"height":null,"weight":null,"totalSportTime":null,"totalExpend":null,"status":1,"isImport":null,"yxUid":null,"blockChainAddress":null,"birthday":null,"batchType":null,"isSubscribeOfficial":null,"registerChannel":0,"thirdUid":null,"aliOpenId":null,"bgImg":null}],"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjdXN0b21QYXJhbWV0ZXIiOiJxd2VyMTIzNCIsInVzZXJJZCI6NDE3MjA2MSwiZXhwIjoxNzYyMTQ0NTIwfQ.UYbHs89TIRwz_YEoGFSG1MQkRw-LZFg97Mg6X42yOiE"},"timestamp":1761539720817}
        # return self.__fetch_flashx__(url)
        return self.__post_flashx__(url, data)

    def set_user_info(self, name, member):
        # {"level":1,"province":null,"city":null,"region":null,"height":"166","weight":"50","sportId":1}
        url = f'{api_host}/flash/user/saveFrontUser'
        data = {
            'avatar': member.member_avatar,
            'nickName': name,
            'sex': member.sex,
            'level': member.level,
            'province': None,
            'city': None,
            'region': None,
            'sportId': 1
        }
        return self.__post_flashx__(url, data)

    def set_password(self, password):
        url = f'{api_host}/flash/user/setPwd'
        data = {'pwd': password}
        return self.__post_flashx__(url, data)

    def query_club_member(self, club_id, name):
        keyword = urlencode({'keyword': name})
        url = f'{api_host}/flash/clubMember/searchMember?clubId={club_id}&{keyword}&pageNo=1&pageSize=20&isLoading=true&isHave=true&sportId=1&sortCate=1&sortWay=2'
        print('member url:', url)
        return self.__fetch_flashx__(url)['records']

    def set_user_balance(self, club_id, member_id, balance):
        url = f'{api_host}/flash/clubMember/adminRecharge?reChargeAmount={balance}&type=1&clubId={club_id}&memberId={member_id}&remark=%E8%B0%83%E6%95%B4'
        # return self.__post_flashx__(url, None)
        return self.__fetch_flashx__(url)

    def join_act(self, act_id, group_id, price):
        url = f'{api_host}/flash/activity/applyActivity'
        data = {
            "payAmount": str(price) + ".00",
            "activityId": str(act_id),
            "maleCount": 0,
            "femaleCount": 0,
            "payType": 0,
            "hangPeopleDetails": [],
            "groupId": group_id,
            "applyRemark": "",
            "teamName": "",
            "idNumber": "",
            "birthday": "",
            "xbSex": None,
            "cardType": 1,
            "realName": "",
            "memberRemarkList": [],
            "trackActMemberProjectDoList": [],
            "isBuyNewCard": 0,
            "isUseFreePlayEquity": 0,
            "city": "北京市",
            "signupType": 1,
            "isHitInfo": 0
        }
        return self.__post_flashx__(url, data)

    def user_detail(self):
        url = f'{api_host}/flash/activity/clubMemberActRecord?clubMemberId=408339&clubId=8474&keyWord=&pageSize=10&pageNo=1&longitude=116.40717315673828&latitude=39.90468978881836&isLoading=false&isHave=true&type=-1&actStatus=0&actTime=-1&sportId=0'
        return self.__fetch_flashx__(url)
        # url = f'{api_host}/flash/clubMember/memberInfo?memberId=1830046&sportId=1'
        # return self.__fetch_flashx__(url)

    def fetch_temp_admin(self, act_id):
        url = list_temp_admin_url.format(act_id)
        # print('url:', url)
        return self.__fetch_flashx__(url)

    def add_temp_admin(self, act_id, member_id_list):
        data = {"activityId": f"{act_id}", "memberIdList": member_id_list}
        url = add_temp_admin_url
        return self.__post_flashx__(url, data)

    def join_club(self, club_id):
        url = f'{api_host}/flash/club/join'
        data = {'clubId': club_id}
        return self.__post_flashx__(url, data)

    def __post_flashx__(self, url, data):
        # 设置自定义请求头
        headers = {
            'Accept': '*/*',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept_Language': 'zh-CN,zh;q=0.9',
            'Content-Type': 'application/json',
            'X-Access-Token': self.flash_token,
            'Request-Channel': 'APP',
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Html5Plus/1.0 (Immersed/20) uni-app',
            # 'xweb_xhr': '1',
            # 'Sec-Fetch-Dest': 'empty',
            # 'Sec-Fetch-Mode': 'cors',
            # 'Sec-Fetch-Site': 'cross-site',
            'Host': 'flash.flashxsport.com',
            'Connection': 'keep-alive'
            # 'Referer': 'https://servicewechat.com/wxbb50595cab69d719/607/page-frame.html'
        }

        try:
            print('data:', data)
            print('headers', headers)
            # return None
            # print(f'正在抓取第{page_no}页数据，每页数据{page_size}条')
            # 发送GET请求
            response = requests.post(url, json=data, headers=headers)

            # 检查响应状态码
            if response.status_code == 200:
                json_data = response.json()
                print('post result', json_data)
                if json_data['result']:
                    return json_data['result']
                else:
                    return json_data
            else:
                print(f"请求失败，状态码: {response.status_code}")
                return None

        except requests.exceptions.RequestException as e:
            print(f"请求发生错误: {e}")
            return None
        except json.JSONDecodeError as e:
            print(f"JSON解析错误: {e}")
            return None

    def __fetch_flashx__(self, url):
        response = self.__fetch__(url)
        # print('response:', response)
        # 解析JSON响应
        json_data = response.json()
        # print('get result', json_data)
        # total_count = json_data['result']['total']
        # users = json_data['result']['records']
        # rows = len(users)
        # print("成功获取%s条数据" % rows)
        # print(json.dumps(json_data, indent=4))
        if json_data['code'] and json_data['code'] == 403:
            print('无法访问，可能是token已过期', json_data)
            raise Exception('需要重新配置访问token')
        if json_data['result']:
            return json_data['result']
        else:
            return json_data

    def __fetch__(self, url):
        # 设置自定义请求头
        headers = {
            'Accept': '*/*',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept_Language': 'zh-CN,zh;q=0.9',
            'X-Access-Token': self.flash_token,
            'Request-Channel': 'APP',
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Html5Plus/1.0 (Immersed/20) uni-app',
            'Host': 'flash.flashxsport.com',
            'Connection': 'keep-alive'
        }

        try:
            # print(f'正在抓取第{page_no}页数据，每页数据{page_size}条')
            # 发送GET请求
            response = requests.get(url, headers=headers)

            # 检查响应状态码
            if response.status_code == 200:
                return response
            else:
                print(f"请求失败，状态码: {response.status_code}")
                return None

        except requests.exceptions.RequestException as e:
            print(f"请求发生错误: {e}")
            return None
        except json.JSONDecodeError as e:
            print(f"JSON解析错误: {e}")
            return None

    def create_test(self):
        data = {
            "id": 2919390,
            "version": None,
            "createTime": None,
            "updateTime": None,
            "delFlag": 0,
            "publisherUid": 835265,
            "adminUid": None,
            "clubId": 10727,
            "placeId": 30875,
            "sportId": 1,
            "activityTitle": "临时活动哈哈哈",
            "activityAvatar": "https://oss.flashxsport.com/flashUpload/activity/5fb2276179c145629b283109e29c9107.png",
            "activityStatus": None,
            "activityDate": "2025-11-13",
            "endDate": "2025-11-13",
            "startTime": "17:00",
            "endTime": "19:00",
            "startTimestamp": None,
            "endTimestamp": None,
            "cancelApplyDeadline": 12,
            "paymentType": 2,
            "activityType": 0,
            "organizeType": 0,
            "bond": 0,
            "bondWay": 0,
            "contactPerson": "满山饭",
            "wxCode": "13810193718",
            "phone": "13810193718",
            "levelLower": 1,
            "levelUpper": 8,
            "des": "",
            "isRefund": None,
            "isTakeRate": None,
            "activityPics": "",
            "isFemaleDiscount": 0,
            "femaleDiscountAmount": 0,
            "isEarlyDiscount": 0,
            "earlyDay": None,
            "earlyTime": "",
            "earlyDiscountAmount": 0,
            "activityQrcode": None,
            "amountPath": 0,
            "placeNum": "",
            "type": 0,
            "isOpenSign": 1,
            "isPlatShow": 1,
            "isAllowQueue": 1,
            "isAllowExchange": 1,
            "isAllowHang": 1,
            "hangCount": -1,
            "isBuyInsure": 0,
            "isOpenClubInsure": 0,
            "isShowRealName": 1,
            "isRealName": 0,
            "isOpenSignRegular": 0,
            "openAdvanceDay": 3,
            "openSignTime": "12:00",
            "remarkReason": None,
            "isApplyRemark": 0,
            "remarkDesc": None,
            "remarkExample": None,
            "openAaDetail": 1,
            "copyInfoRemark": "",
            "isAaOpenMemberDiscount": 0,
            "isAutoCancel": 0,
            "autoCancelHours": 1,
            "autoCancelCount": 6,
            "insurePlanId": None,
            "isUnifyBuyInsure": 0,
            "pubChannel": None,
            "htmlContent": None,
            "isSupportCardPay": 1,
            "isSupportFreePlay": 0,
            "freePlayCount": 0,
            "isSupportRaffle": 1,
            "isAllowRaffleList": 0,
            "isVipDiscount": 1,
            "discountWay": None,
            "city": None,
            "region": None,
            "address": None,
            "latitude": 39.940308,
            "longitude": 116.124437,
            "reminderAfterText": "",
            "reminderAfterImgUrl": "",
            "placeName": "星苒羽超篮羽运动中心",
            "province": None,
            "placeAddress": "北京市石景山区双峪路71号D座一层103号(免费停车)",
            "activityTime": "11-13 周四 17:00-19:00",
            "startTimeList": [
                "17",
                "00"
            ],
            "endTimeList": [
                "当日",
                "19",
                "00"
            ],
            "dateList": [
                "2025-11-14"
            ],
            "needMemberNum": None,
            "maleLevelLower": None,
            "maleLevelUpper": None,
            "femaleLevelLower": None,
            "femaleLevelUpper": None,
            "showCost": "¥20",
            "isWeekPublish": 0,
            "activityGroupDoList": [
                {
                    "id": 4568940,
                    "version": 0,
                    "createTime": "2025-11-13 09:03:24",
                    "updateTime": "2025-11-13 17:02:01",
                    "delFlag": 0,
                    "activityId": 2919390,
                    "groupName": None,
                    "needMemberNum": 6,
                    "applyNum": 0,
                    "applyAmount": 20,
                    "maleLevelLower": 1,
                    "maleLevelUpper": 8,
                    "femaleLevelLower": 1,
                    "femaleLevelUpper": 8,
                    "placeNum": "",
                    "groupSort": 0
                }
            ],
            "activityRemarkParamDto": {
                "activityId": 2919390,
                "remarkReason": None,
                "activityRemarkDtoList": []
            },
            "placeDo": {
                "id": 30875,
                "version": 0,
                "createTime": "2024-08-13 10:41:25",
                "updateTime": "2025-03-29 07:22:38",
                "delFlag": 0,
                "placeName": "星苒羽超篮羽运动中心",
                "score": "4.0",
                "isBusiness": 1,
                "phone": "13811869178",
                "businessDate": None,
                "city": "北京市",
                "region": "石景山区",
                "address": "北京市石景山区双峪路71号D座一层103号(免费停车)",
                "type": None,
                "albumPics": "flashUpload/userAvatar/tmp_e349d9a887ed3a59495bbaee6b0b6f92_30531133836630052.jpg,flashUpload/userAvatar/tmp_97f66dc885a4fbfa0f05821bd365761a_30531133695201750.jpg,flashUpload/userAvatar/tmp_2e3e4d52d43d8a8f7fff4758e38e5419_24118056062969364.jpg,flashUpload/userAvatar/tmp_d1544423eb9b4966737855842e764216_30531133853932628.jpg,flashUpload/userAvatar/tmp_b0d6bdd56854f47a50937e1ae6343b39_30531132988050055.jpg,flashUpload/userAvatar/tmp_810e3acb71b92b5775277a4b8d139a7f_30531133552472001.jpg",
                "latitude": 39.940308,
                "longitude": 116.124437,
                "sportId": None,
                "sportIds": "1",
                "citycode": None,
                "adcode": None,
                "businessArea": None,
                "gaodeId": None,
                "doorPics": "flashUpload/userAvatar/tmp_d01dba32ad707194e2a19a21c6bfb36d_24117925273875869.jpg",
                "idCardStart": "flashUpload/userAvatar/tmp_9e530824437d5b61e115e312f905d505_24118265317214365.jpg",
                "idCardEnd": "flashUpload/userAvatar/tmp_e59235fc2c8a63f7e4139d33cbb1a5b6_24118270339586679.jpg",
                "businessLicense": "flashUpload/userAvatar/tmp_55ee8e2ac8ff9a6c43ca7e298c1969a1_24118260150350710.jpg",
                "addressDetail": None,
                "venueDetail": "免费停车、专业场地灯光木地板地胶、可提供专业培训",
                "userId": 2200899,
                "useChannel": 0
            },
            "isLike": 0,
            "maxMemberCount": None,
            "maxTeamCount": None,
            "weekNumber": 4,
            "insurancePlanDo": None,
            "actInsuranceApplicantDo": {},
            "trackActConfigDto": None,
            "activityProjectDtoList": None,
            "coachId": None,
            "coachName": None,
            "insurePlanName": "",
            "isExtendNextDay": 0
        }

        self.__post_flashx__(api_host + '/flash/activity/publishActivity', data)


if __name__ == "__main__":
    token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjdXN0b21QYXJhbWV0ZXIiOiJxd2VyMTIzNCIsInVzZXJJZCI6ODM1MjY1LCJleHAiOjE3NjM2MzY4MTl9.kyn-jE04AYnFS8I1UGpsiNlIXYHAfTEL0owYaEsjvXo'
    http = HttpHelper()
    http.set_flash_token(token)
    http.get_act_group(2896124)['actGroups'][0]['groupId']
